import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';

import 'xin_he_qr_scanner_logic.dart';

class XinHeQrScannerPage extends StatelessWidget {
  XinHeQrScannerPage({Key? key}) : super(key: key);

  final logic = Get.put(XinHeQrScannerLogic());
  final state = Get.find<XinHeQrScannerLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Expanded(flex: 4, child: _buildQrView(context)),
      ],
    );
  }

  Widget _buildQrView(BuildContext context) {
    // For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
    var scanArea = (MediaQuery.of(context).size.width < 400 ||
        MediaQuery.of(context).size.height < 400)
        ? 150.0
        : 300.0;
    // To ensure the Scanner view is properly sizes after rotation
    // we need to listen for Flutter SizeChanged notification and update controller
    return QRView(
      key: logic.qrKey,
      onQRViewCreated:_onQRViewCreated,
      overlay: QrScannerOverlayShape(
          borderColor: Colors.red,
          borderRadius: 10,
          borderLength: 30,
          borderWidth: 10,
          cutOutSize: scanArea),
      onPermissionSet: (ctrl, p) => _onPermissionSet(context, ctrl, p),
    );
  }


  void _onQRViewCreated(QRViewController controller) {
    logic.controller?.dispose();
   logic.controller = controller;
   controller.scannedDataStream.listen((scanData) async{

     logic.controller!.stopCamera();
     logic.controller!.resumeCamera();


     Get.back(result: scanData.code??'');
     });

  }

  void _onPermissionSet(BuildContext context, QRViewController ctrl, bool p) {
    log('${DateTime.now().toIso8601String()}_onPermissionSet $p');
    if (!p) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('no Permission')),
      );
    }
  }

}
